<template>
  <div class="page-search">
    <div class="search-header">
      <div class="back" @click="handleBack">
        <van-icon name="arrow-left"></van-icon>
      </div>
      <div class="input">
        <form @submit.prevent="handleSearch">
          <input v-model.trim="keywords" type="search" placeholder="O que procuras?" />
        </form>
      </div>
    </div>
    <div class="history">
      <div class="title">PESQUISAS RECENTES</div>
      <div class="list">
        <div class="item" v-for="(item, index) in history" :key="index" @click="handleDetail(item)">
          <div class="left">{{ item }}</div>
          <div class="right" @click.stop="handleRemove(index)">
            <van-icon name="cross"></van-icon>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Api from "@/api";
import { Domain } from "@/constants";
export default {
  name: "Search",
  data() {
    return {
      keywords: "",
      history: [],
    };
  },
  mounted() {
    const historyList = localStorage.getItem("HISTORY");
    if (historyList) {
      this.history = JSON.parse(historyList);
    }
  },
  methods: {
    handleBack() {
      this.$router.back();
    },
    handleSearch() {
      this.history.push(this.keywords);
      localStorage.setItem("HISTORY", JSON.stringify(this.history));
      this.$router.push({
        path: "/result",
        query: {
          keywords: this.keywords,
        },
      });
    },
    handleRemove(index) {
      this.history.splice(index, 1);
      localStorage.setItem("HISTORY", JSON.stringify(this.history));
    },
    handleDetail(item) {
      this.$router.push({
        path: "/result",
        query: {
          keywords: item,
        },
      });
    },
  },
};
</script>
<style lang="less" scoped>
.page-search {
  position: relative;
  .search-header {
    display: flex;
    align-items: center;
    height: 50px;
    background: #fff;
    padding: 0 16px;
    box-sizing: border-box;
    .back {
      flex: none;
      margin-right: 16px;
      display: flex;
      align-items: center;
    }
    .input {
      flex: auto;
      width: 0;
      input {
        height: 35px;
        line-height: 35px;
        width: 100%;
        border: none;
        outline: none;
      }
    }
  }
  .history {
    .title {
      line-height: 40px;
      font-size: 14px;
      font-weight: bold;
      color: #000;
      padding: 0 16px;
    }
    .list {
      .item {
        background: #fff;
        height: 45px;
        display: flex;
        align-items: center;
        padding: 0 16px;
        box-sizing: border-box;
        border-bottom: 1px solid #ededed;
        .left {
          flex: auto;
          width: 0;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .right {
          flex: none;
          display: flex;
          align-items: center;
        }
      }
    }
  }
}
</style>
